package com.generator.controller;


import com.generator.service.GeneratorService;
import com.generator.utils.DateUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;

/**
 * 代码生成器
 *
 * @author lipengjun
 * @email 939961241@qq.com
 * @date 2017年1月3日 下午6:35:28
 */
@Controller
public class GeneratorController {


    @Autowired
    @Qualifier("GeneratorServiceImpl")
    private GeneratorService sysGeneratorService;

    /**
     * 生成代码
     */
    @RequestMapping("/code")
    public void code(HttpServletRequest request, HttpServletResponse response,
                     @RequestParam(value = "tableNames",required = true) String[] tableNames,
                     @RequestParam(value = "package",required = false) String packageName
                     ) throws IOException {


        byte[] data = sysGeneratorService.generatorCode(tableNames,packageName);

        response.reset();
        response.setHeader("Content-Disposition", "attachment; filename=\"AutoCode"
                + DateUtils.format(new Date(), DateUtils.DATE_TIME_PATTERN_YYYY_MM_DD_HH_MM_SS_SSS) + ".zip\"");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");

        IOUtils.write(data, response.getOutputStream());
    }
}
